package com.example.rentingapp.fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;

import com.example.rentingapp.activity.HousingDetailsActivity1;
import com.example.rentingapp.api.Api;
import com.example.rentingapp.api.ApiConfig;
import com.example.rentingapp.api.TtitCallback;
import com.example.rentingapp.adapter.HouseAdapter;
import com.example.rentingapp.R;
import com.example.rentingapp.enetity.HouseEntity;
import com.example.rentingapp.enetity.HouseResponse;
import com.example.rentingapp.util.StringUtils;
import com.example.rentingapp.view.CommonFilterPop;
import com.example.rentingapp.view.DoubleFilterPop;
import com.google.gson.Gson;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class SearchFragment extends BaseFragment implements View.OnClickListener {
    private final String[] parent_String_mLocation = {"广  州", "深  圳", "佛  山", "东  莞", "中  山", "珠  海", "江  门", "肇  庆", "惠  州",
            "汕  头", "潮  州", "揭  阳", "汕  尾", "湛  江", "茂  名", "阳  江", "云  浮", "韶  关", "清  远", "梅  州", "河  源"};
    private final String[] parent_String_mType = {"租  期", "类  型"};
    private final String[] parent_String_mRent = {"全  部", "8000 +", "5000 - 8000", "3500 - 5000", "2500 - 3500", "1500 - 2500", "0 - 1500"};
    private final String[][] children_String_mLocation = {{"全   部"},
            {"全   部", "福田区", "罗湖区", "盐田区", "南山区", "宝安区", "龙岗区", "龙华区", "坪山区", "光明区", "大鹏新区"},
            {"全   部"}, {"全   部"}, {"全   部"}, {"全   部"}, {"全   部"}, {"全   部"}, {"全   部"}, {"全   部"}, {"全   部"},
            {"全   部"}, {"全   部"}, {"全   部"}, {"全   部"}, {"全   部"}, {"全   部"}, {"全   部"}, {"全   部"}, {"全   部"}};
    private final String[][] children_String_mType = {{"长租&短租", "长  租", "短  租"}, {"整租&合租", "整  租", "合  租"}};

    private HouseAdapter houseAdapter = null;
    private List<HouseEntity> datas = new ArrayList<>();
    private DoubleFilterPop doubleFilterPop = null;//筛选pop
    private CommonFilterPop commonFilterPop = null;
    private ListView listView;
    private CheckBox cb_quyu, cb_zujin, cb_fangxing;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    houseAdapter = new HouseAdapter(datas, getContext());
                    listView.setAdapter(houseAdapter);
                    houseAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    protected int initLayout() {
        return R.layout.fragment_search;
    }

    @Override
    protected void initView() {
        listView = mRootView.findViewById(R.id.listview);
        cb_quyu = mRootView.findViewById(R.id.cb_quyu);
        cb_zujin = mRootView.findViewById(R.id.cb_zujin);
        cb_fangxing = mRootView.findViewById(R.id.cb_fangxing);
    }

    @Override
    protected void initData() {
        cb_quyu.setOnClickListener(this);
        cb_zujin.setOnClickListener(this);
        cb_fangxing.setOnClickListener(this);

        findHouseByLocation("深圳");//根据location搜索房源

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String house_id = String.valueOf(datas.get(position).getHouse_id());
                insertVal("house_id", house_id);//点击房源详情时，把house_user_id存入本地

                transfer(HousingDetailsActivity1.class, (int) houseAdapter.getItemId(position));
            }
        });

        //下拉刷新框架
        RefreshLayout refreshLayout = (RefreshLayout) getView().findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(1000/*,false*/);//传入false表示刷新失败
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(1000/*,false*/);//传入false表示加载失败
            }
        });
    }

    @Override
    public void onClick(View v) {
        //区域
        if (cb_quyu.isChecked()) {
            doubleFilterPop = new DoubleFilterPop(getActivity(), parent_String_mLocation, children_String_mLocation, selectCategory_mLocation);
            //设置popupWindow显示的位置，参数依次是参照View，x轴的偏移量，y轴的偏移量
            doubleFilterPop.showAsDropDown(v, 0, 45);
            //添加doubleFilterPop消失的监听
            doubleFilterPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    cb_quyu.setChecked(false);
                    doubleFilterPop = null;
                }
            });
        }

        //房屋类型
        if (cb_fangxing.isChecked()) {
            doubleFilterPop = new DoubleFilterPop(getActivity(), parent_String_mType, children_String_mType, selectCategory_mType);
            //设置popupWindow显示的位置，参数依次是参照View，x轴的偏移量，y轴的偏移量
            doubleFilterPop.showAsDropDown(v, 0, 45);
            //添加doubleFilterPop消失的监听
            doubleFilterPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    cb_fangxing.setChecked(false);
                    doubleFilterPop = null;
                }
            });
        }

        //价格范围
        if (cb_zujin.isChecked()) {
            commonFilterPop = new CommonFilterPop(getActivity(), parent_String_mRent, selectCategory_mRent);
            //设置popupWindow显示的位置，参数依次是参照View，x轴的偏移量，y轴的偏移量
            commonFilterPop.showAsDropDown(v, 0, 50);
            //添加commonFilterPop消失的监听
            commonFilterPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    cb_zujin.setChecked(false);
                    commonFilterPop = null;
                }
            });
        }
    }

    //选择完成DoubleFilterPop回调接口
    private DoubleFilterPop.SelectCategory selectCategory_mLocation = new DoubleFilterPop.SelectCategory() {//区域回调接口
        @Override
        public void selectCategory(int parentSelectPosition, int childrenSelectPosition) {
            String parentStr = parent_String_mLocation[parentSelectPosition];
            String childrenStr = children_String_mLocation[parentSelectPosition][childrenSelectPosition];
            parentStr = parentStr.replace(" ", "");
            childrenStr = childrenStr.replace(" ", "");
            if (!StringUtils.isEmpty(parentStr) && !StringUtils.isEmpty(childrenStr)) {
                if (childrenStr.equals("全部")) {
                    findHouseByLocation(parentStr);
                } else {
                    findHouseByAddress(childrenStr);
                }
            }
        }
    }, selectCategory_mType = new DoubleFilterPop.SelectCategory() {//房屋类型回调接口
        @Override
        public void selectCategory(int parentSelectPosition, int childrenSelectPosition) {
            String parentStr = parent_String_mType[parentSelectPosition];
            String childrenStr = children_String_mType[parentSelectPosition][childrenSelectPosition];
            parentStr = parentStr.replace(" ", "");
            childrenStr = childrenStr.replace(" ", "");
            if (!StringUtils.isEmpty(parentStr) && !StringUtils.isEmpty(childrenStr)) {
                if (parentStr.equals("租期")) {
                    findHouseByTimeType(childrenStr);
                } else if (parentStr.equals("类型")) {
                    findHouseByHomeType(childrenStr);
                }
            }
        }
    };

    //选择完成CommonFilterPop回调接口
    private CommonFilterPop.SelectCategory selectCategory_mRent = new CommonFilterPop.SelectCategory() {
        @Override
        public void selectCategory(int parentSelectPosition) {//价格范围回调接口
            String parentStr = parent_String_mRent[parentSelectPosition];
            showToast("价格范围" + parentStr.replace(" ", ""));
        }
    };

    private void findHouseByLocation(String location) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("location", location);
        Api.config(ApiConfig.FIND_HOUSE_BY_LOCATION, params).postRequest(getActivity(), new TtitCallback() {
            @Override
            public void onSuccess(final String res) {
                Log.e("onSuccess", res);
                Gson gson = new Gson();
                HouseResponse houseResponse = gson.fromJson(res, HouseResponse.class);
                if (houseResponse.getSuccess() == true) {
                    List<HouseEntity> list = houseResponse.getDatas();
                    if (list != null && list.size() > 0) {
                        datas = list;
                        mHandler.sendEmptyMessage(0);
                    }
                } else {
                    showToastSync("该城市无房源");
                }
            }

            @Override
            public void onFailure(Exception e) {
                Log.e("onFailure", e.toString());
            }
        });
    }

    private void findHouseByAddress(String address) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("address", address);
        Api.config(ApiConfig.FIND_HOUSE_BY_ADDRESS, params).postRequest(getActivity(), new TtitCallback() {
            @Override
            public void onSuccess(final String res) {
                Log.e("onSuccess", res);
                Gson gson = new Gson();
                HouseResponse houseResponse = gson.fromJson(res, HouseResponse.class);
                if (houseResponse.getSuccess() == true) {
                    List<HouseEntity> list = houseResponse.getDatas();
                    if (list != null && list.size() > 0) {
                        datas = list;
                        mHandler.sendEmptyMessage(0);
                    }
                } else {
                    showToastSync("该地区无房源");
                }
            }

            @Override
            public void onFailure(Exception e) {
                Log.e("onFailure", e.toString());
            }
        });
    }

    private void findHouseByTimeType(String time_type) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("time_type", time_type);
        Api.config(ApiConfig.FIND_HOUSE_BY_TIMETYPE, params).postRequest(getActivity(), new TtitCallback() {
            @Override
            public void onSuccess(final String res) {
                Log.e("onSuccess", res);
                Gson gson = new Gson();
                HouseResponse houseResponse = gson.fromJson(res, HouseResponse.class);
                if (houseResponse.getSuccess() == true) {
                    List<HouseEntity> list = houseResponse.getDatas();
                    if (list != null && list.size() > 0) {
                        datas = list;
                        mHandler.sendEmptyMessage(0);
                    }
                } else {
                    showToastSync("该租期类型无房源");
                }
            }

            @Override
            public void onFailure(Exception e) {
                Log.e("onFailure", e.toString());
            }
        });
    }

    private void findHouseByHomeType(String home_type) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("home_type", home_type);
        Api.config(ApiConfig.FIND_HOUSE_BY_HOMETYPE, params).postRequest(getActivity(), new TtitCallback() {
            @Override
            public void onSuccess(final String res) {
                Log.e("onSuccess", res);
                Gson gson = new Gson();
                HouseResponse houseResponse = gson.fromJson(res, HouseResponse.class);
                if (houseResponse.getSuccess() == true) {
                    List<HouseEntity> list = houseResponse.getDatas();
                    if (list != null && list.size() > 0) {
                        datas = list;
                        mHandler.sendEmptyMessage(0);
                    }
                } else {
                    showToastSync("该租房类型无房源");
                }
            }

            @Override
            public void onFailure(Exception e) {
                Log.e("onFailure", e.toString());
            }
        });
    }

}